package com.augurit.gzcgwsp.jzfqwczz.service.impl;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.HqlUtils;
import com.augurit.common.util.PageUtils;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.jzfqwczz.convert.YwYnJzfqwczcJbxxConvertor;
import com.augurit.gzcgwsp.jzfqwczz.dao.YwYnJzfqwczcJbxxDao;
import com.augurit.gzcgwsp.jzfqwczz.entity.YwYnJzfqwczcJbxx;
import com.augurit.gzcgwsp.jzfqwczz.service.IYwYnJzfqwczcShhzQxService;
import com.augurit.gzcgwsp.jzfqwczz.web.form.YwYnJzfqwczcJbxxForm;
import com.augurit.gzcgwsp.sendNotice.service.IExchangeStateService;
import com.augurit.gzcgwsp.sendNotice.service.IYwMtbjlshInfoService;
import com.augurit.gzcgwsp.sendNotice.service.IYwWebserviceForWbService;
import com.augurit.gzcgwsp.sendNotice.service.IYwWebserviceInfoService;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.ywcmn.service.IYwComQyxxService;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjclService;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjcllistService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComQyxxForm;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjclForm;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjcllistForm;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.common.service.impl.WfBusClientServiceImpl;

@Service
@Transactional
public class YwYnJzfqwczcShhzQxServiceImpl extends WfBusClientServiceImpl<YwYnJzfqwczcJbxxForm> implements IYwYnJzfqwczcShhzQxService{

	@Autowired
	private YwYnJzfqwczcJbxxDao ywYnJzfqwczcJbxxDao;
    @Autowired
    private IYwComQyxxService ywComQyxxService;
    @Autowired
    private IYwComSjclService sjclService;
    @Autowired
    private IYwComSjcllistService ywComSjcllistService;
    @Autowired
    private IYwComSjclService ywComSjclService;
    @Autowired
    private IYwMtbjlshInfoService ywMtbjlshInfoService;
    @Autowired
	private IYwWebserviceInfoService ywWebserviceInfoService;
    @Autowired
    private IYwWebserviceForWbService ywWebserviceForWbService;
    @Autowired
    private IExchangeStateService exchangeStateService;
    @Autowired
    private IWfServiceEX wfServiceEX;
    
	/**
	 * ��������ȡForm����
	 */
	@Transactional(readOnly = true)
	public YwYnJzfqwczcJbxxForm get(Long id) {
		YwYnJzfqwczcJbxx entity = ywYnJzfqwczcJbxxDao.get(id);
		YwYnJzfqwczcJbxxForm form=YwYnJzfqwczcJbxxConvertor.convertVoToForm(entity);
		YwComSjcllistForm sjclListForm=new YwComSjcllistForm();
        YwComQyxxForm qyxxform = ywComQyxxService.get(form.getQyid());
        sjclListForm.setAjid(id);
        sjclListForm.setTplcode("jzljczzqx_shhz");
        List<YwComSjcllistForm> sjclList = ywComSjcllistService.getList(sjclListForm);
        YwComSjclForm fkForm = new YwComSjclForm();
        fkForm.setFkid(form.getQyid());
        fkForm.setAjid(id);
        fkForm.setTplcode("jzljczzqx_shhz");
        List<YwComSjclForm> sjclTpl = ywComSjclService.getList(fkForm);
        for (YwComSjcllistForm listForm : sjclList) {
            boolean hasExists = false;
            for (YwComSjclForm tplForm : sjclTpl) {
                if (tplForm.getTplid() != null && listForm.getId().longValue() == tplForm.getTplid().longValue()) {
                    if (StringUtils.isNotBlank(tplForm.getFilepath())) {
                        listForm.setState("1");
                        listForm.setHasfile("1");
                        listForm.setFilename(tplForm.getFilename());
                        listForm.setFilepath(tplForm.getFilepath());
                        listForm.setFiletype(tplForm.getFiletype());
                    } else {
                        listForm.setState("0");
                        listForm.setHasfile("0");
                    }
                    if (tplForm.getYjs() != null) {
                        listForm.setYjs(Long.valueOf(tplForm.getYjs()));
                    }
                    if (tplForm.getFyjs() != null) {
                        listForm.setFyjs(Long.valueOf(tplForm.getFyjs()));
                    }
                    listForm.setClid(tplForm.getId());
                    if ("1".equals(listForm.getSfdz())) {
                        listForm.setDisabled("1");
                    } else {
                        listForm.setDisabled("0");
                        if (tplForm.getSfdz() == null) {
                            listForm.setSfdz("0");
                        } else {
                            listForm.setSfdz(tplForm.getSfdz());
                        }
                    }
                    hasExists = true;
                }
            }
            if (!hasExists) {
                listForm.setState("0");
                listForm.setHasfile("0");
                if ("1".equals(listForm.getSfdz())) {
                    listForm.setDisabled("1");
                } else {
                    listForm.setDisabled("0");
                }
            }
        }
        form.setAcceptNo2(form.getAcceptNo());
        form.setCbyw2(form.getCbyw());
        form.setCbyw3(form.getCbyw());
        form.setCbyw4(form.getCbyw());
        form.setSjr2(form.getSjr());
        form.setSqdw2(form.getSqdw());
        form.setSqdw3(form.getSqdw());
        form.setSajg2("广州市城市管理委员会");
        form.setSajg(form.getSajg2());
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        YwYnJzfqwczcJbxxConvertor.convertQyxxFormToForm(qyxxform, form);
        if(sjclList.size()>0)
        {
                YwComSjcllistForm sjclForm01=sjclList.get(0);
                form.setTitleRow101(sjclForm01.getTitle());
                form.setTitleRow102(sjclForm01.getTitle());
                form.setFyjsRow101(sjclForm01.getFyjs());
                form.setFyjsRow102(sjclForm01.getFyjs());
                form.setFsRow101(sjclForm01.getYjs()+sjclForm01.getFyjs());
                form.setFsRow102(sjclForm01.getYjs()+sjclForm01.getFyjs());
                if("0".equals(sjclForm01.getSfdz()))
                {
                    form.setSfdzRow101("√");
                    form.setSfdzRow102("√");
                }else{
                    form.setSfdzRow101("√");
                    form.setSfdzRow102("√");
                }
                
                YwComSjcllistForm sjclForm02=sjclList.get(1);
                form.setTitleRow201(sjclForm02.getTitle());
                form.setTitleRow202(sjclForm02.getTitle());
                form.setFyjsRow201(sjclForm02.getFyjs());
                form.setFyjsRow202(sjclForm02.getFyjs());
                form.setFsRow201(sjclForm02.getYjs()+sjclForm02.getFyjs());
                form.setFsRow202(sjclForm02.getYjs()+sjclForm02.getFyjs());
                if("0".equals(sjclForm02.getSfdz()))
                {
                    form.setSfdzRow201("√");
                    form.setSfdzRow202("√");
                }else{
                    form.setSfdzRow201("√");
                    form.setSfdzRow202("√");
                }
                
                YwComSjcllistForm sjclForm03=sjclList.get(2);
                form.setTitleRow301(sjclForm03.getTitle());
                form.setTitleRow302(sjclForm03.getTitle());
                form.setFyjsRow301(sjclForm03.getFyjs());
                form.setFyjsRow302(sjclForm03.getFyjs());
                form.setFsRow301(sjclForm03.getYjs()+sjclForm03.getFyjs());
                form.setFsRow302(sjclForm03.getYjs()+sjclForm03.getFyjs());
                if("0".equals(sjclForm03.getSfdz()))
                {
                    form.setSfdzRow301("√");
                    form.setSfdzRow302("√");
                }else{
                    form.setSfdzRow301("√");
                    form.setSfdzRow302("√");
                }
                
                
                YwComSjcllistForm sjclForm04=sjclList.get(3);
                form.setTitleRow401(sjclForm04.getTitle());
                form.setTitleRow402(sjclForm04.getTitle());
                form.setFyjsRow401(sjclForm04.getFyjs());
                form.setFyjsRow402(sjclForm04.getFyjs());
                form.setFsRow401(sjclForm04.getYjs()+sjclForm04.getFyjs());
                form.setFsRow402(sjclForm04.getYjs()+sjclForm04.getFyjs());
                if("0".equals(sjclForm04.getSfdz()))
                {
                    form.setSfdzRow401("√");
                    form.setSfdzRow402("√");
                }else{
                    form.setSfdzRow401("√");
                    form.setSfdzRow402("√");
                }
        }
        form.setLxr2(form.getYwlxr());
        if(form.getSqDate() != null){
            form.setSqrq2(format.format(form.getSqDate()));
            form.setSqrq3(format.format(form.getSqDate()));
        }
        if(form.getLarq() != null){
            form.setLarq3(format.format(form.getLarq()));
        	form.setLarq4(format.format(form.getLarq()));
        }else{
        	form.setLarq3(format.format(new Date()));
        	form.setLarq4(format.format(new Date()));
        }
		return form;
        //return YwYnJzfqwczcJbxxConvertor.convertVoToForm(entity);
	}
	
	/**
	 * ɾ��Form�����б�
	 */
	public void delete(Long... ids) {
		ywYnJzfqwczcJbxxDao.delete(ids);
	}

	/**
	 * �����������޸ĵ�Form�����б�
	 */
	public void save(YwYnJzfqwczcJbxxForm... forms) {
		if(forms != null)
			for(YwYnJzfqwczcJbxxForm form : forms)
				this.save(form);
	}
	
	/**
	 * �����������޸ĵ�Form����
	 */
	public void save(YwYnJzfqwczcJbxxForm form){
		
		if(form != null){
			YwYnJzfqwczcJbxx entity = null;
			
//            OaDocCodeForm doccodeForm = doccodeService.get(10L);
			
			//׼��VO����
			if(form != null && form.getId() != null){
				entity = ywYnJzfqwczcJbxxDao.get(form.getId());
			}else{
				entity = new YwYnJzfqwczcJbxx();
                form.setAcceptNo(null);
			}

			//保存企业信息
	        YwComQyxxForm qyxxForm = new YwComQyxxForm();
	        if(form.getQyid() == null){
	        	if(StringUtils.isNotBlank(form.getSqdw())){
	            	YwComQyxxForm ywComQyxxForm = ywComQyxxService.getFormBySqdw(form.getSqdw(), "jzljczzqx_shhz");
	            	if(ywComQyxxForm != null){
	            		qyxxForm = ywComQyxxForm;
	            	}
	            }
	        }
	        YwYnJzfqwczcJbxxConvertor.convertFormToQyxxForm(form, qyxxForm);
	        qyxxForm.setTemplateCode("jzljczzqx_shhz");
	        ywComQyxxService.update(qyxxForm);	        
	        form.setQyid(qyxxForm.getId());
	        
	        boolean isNewForm = false;
	        if (StringUtils.isBlank(form.getAcceptNo())) {
	        	//生成政务中心统一查询编号 开始
				Map<String,String> serialNoAndPasswordMap = null;
	        	if("Y".equals(form.getSendNotice())){//网办，1
	        		serialNoAndPasswordMap = ywMtbjlshInfoService.getSerialNoAndPassword("1");
	        	}else{//大厅，0
	        		serialNoAndPasswordMap = ywMtbjlshInfoService.getSerialNoAndPassword("0");
	        	}
	        	String serialNo = serialNoAndPasswordMap.get("serialNo");
	        	String password = serialNoAndPasswordMap.get("password");
				form.setSerialNo(serialNo);
				form.setPassword(password);
				form.setAcceptNo(serialNo);
	    		//生成政务中心统一查询编号 结束
	            isNewForm = true;
	        }
	        String acceptNo="";
	        if(entity!=null && StringUtils.isNotBlank(entity.getAcceptNo())){//有时会出现acceptno2和acceptno不一致
	        	 acceptNo=entity.getAcceptNo();
	        	 form.setAcceptNo(acceptNo);
	        }
			//����ֵת��
			YwYnJzfqwczcJbxxConvertor.convertFormToVo(form, entity);
			 if(entity!=null){
		        	entity.setAcceptNo(acceptNo);
		        }
			//����
			ywYnJzfqwczcJbxxDao.save(entity);
			
			//����ID����ֵ
			form.setId(entity.getId());
			if (isNewForm) {
                sjclService.updateByNewForm(form.getId());
            }
		}
	}

	/**
	 * ���Form����Ĳ�ѯ��������ҳ��ѯ
	 */
	@Transactional(readOnly = true)
	public Page<YwYnJzfqwczcJbxxForm> search(Page<YwYnJzfqwczcJbxxForm> page, YwYnJzfqwczcJbxxForm form) {
		// �����µķ�ҳ����
		Page pg = PageUtils.newPageInstance(page);
		
		// ��ѯ��估����
		StringBuffer hql = new StringBuffer("from YwYnJzfqwczcJbxx ps where 1=1");
		List values = new ArrayList();
		
		// ��ѯ����
		if(form != null){
			
		}
		
		//����
		hql.append(HqlUtils.buildOrderBy(page, "ps"));
		
		// ִ�з�ҳ��ѯ����
		ywYnJzfqwczcJbxxDao.findPage(pg, hql.toString(), values);
		
		// ת��ΪForm�����б?��ֵ��ԭ��ҳ������
		List<YwYnJzfqwczcJbxxForm> list = YwYnJzfqwczcJbxxConvertor.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}
	
	/**
	 * ��ݹ��������б�����ҳ��ѯ
	 */
	@Transactional(readOnly = true)
	public Page<YwYnJzfqwczcJbxxForm> search(Page<YwYnJzfqwczcJbxxForm> page, List<PropertyFilter> filters) {
		// �����µķ�ҳ����
		Page<YwYnJzfqwczcJbxx> pg = PageUtils.newPageInstance(page);
		
		// ������������ҳ���Ҷ���
		ywYnJzfqwczcJbxxDao.findPage(pg, filters);
		
		// ת��ΪForm�����б?��ֵ��ԭ��ҳ������
		List<YwYnJzfqwczcJbxxForm> list = YwYnJzfqwczcJbxxConvertor.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}
	
	public void changeYslState(Long id,Long state,String yslThyy) {
    	StringBuffer sql = new StringBuffer();
    	sql.append("update YwYnJzfqwczcJbxx t set t.ysl="+state);
    	if(StringUtils.isNotBlank(yslThyy)){
    		sql.append(" ,t.yslThyy='"+yslThyy+"'");
    	}
    	sql.append(" where t.id="+id);
    	ywYnJzfqwczcJbxxDao.getSession().createQuery(sql.toString()).executeUpdate();
    	System.out.println("处置证区县-损坏换证 收件");
    }
	
	/**
	 * 导入余泥处-处置证-新增发证-检查表的附件
	 * @param ajid 案件ID
	 * @param fjFlag 附件标志
	 * @param uploadFile 流
	 * @throws Exception
	 */
	public String uploadJcbFj(long ajid, String fjFlag,String fjOldName,String fjType, InputStream uploadFile)throws Exception{
		// 随机生成文件名后缀
		int bytesum = 0;
		int byteread = 0;
		String formatDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		int random = new Random().nextInt(1000000);
		String name = formatDate+random+"."+fjType;
		String address = "/resources/AttacheFile/";
		String address2 = "F:/guowei/install/apache-tomcat-6.0.18/Tomcat 6.0/webapps/gzcgwsp/resources/AttacheFile/";
		FileOutputStream fs = new FileOutputStream(address2+name);
		String sql = "update YwYnJzfqwczcJbxx jz set jz."+fjFlag+"='"+address+name+"', jz."+fjFlag+"name='"+fjOldName+"',jz."+fjFlag+"type='"+fjType+"' where jz.id="+ajid;
		System.out.println("sql = "+sql);
		try{
			Query query = ywYnJzfqwczcJbxxDao.getSession().createQuery(sql);
			query.executeUpdate();
			byte[] buffer = new byte[1024];
			while ((byteread = uploadFile.read(buffer)) != -1) {
				bytesum += byteread; // 字节数 文件大小
				fs.write(buffer, 0, byteread);
			}
			uploadFile.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return address+name;
	}
    
    public String wfBusYslTuih(YwYnJzfqwczcJbxxForm form,LoginUserForm loginUser) throws Exception {
    	String  loginUserName = loginUser.getUser().getUserName();
    	WfBusInstanceTaskForm taskForm = new WfBusInstanceTaskForm();
		taskForm.setHandleComments("资料不全，不予受理。");
		//把审批状态数据保存到ywWebserviceInfo ，交换给方欣
		ywWebserviceInfoService.saveYwWebserviceInfo(form.getSarq(), form.getAcceptNo(), form.getCbyw(), form.getYwlxr(), form.getSjr(), form.getSqdw(), 
				form.getBusinessCode(), form.getApprovalNo(), loginUserName, loginUser.getOrg().getOrgName(), "ysl", new Date(), false, "预受理", taskForm);
//		System.out.println("form.getYslThyy() = "+java.net.URLDecoder.decode(form.getYslThyy(),"UTF-8"));
		this.changeYslState(form.getId(), 0L,taskForm.getHandleComments());
		
		//（网办）交换到市民网页
		Map map=exchangeStateService.buildMap(loginUser, null, form.getId().toString(), form.getTemplateCode(), false);
		String durationExpression = wfServiceEX.getDurationExpressionByTemplateCode(form.getTemplateCode());
		ywWebserviceForWbService.setValueAndSaveYwWebserviceForWb(loginUserName,form.getTemplateCode(),
				form.getId().toString(),durationExpression,"001",taskForm.getHandleComments(), map);
    	return null;
    }
}
